﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Web;
using Service.Core;
using Service.Core.Interface;
using Service.Core.Result;
using Tools;
using Web.BML.AnalysisData;
using Web.BML.CoreData;
using Web.Models.AnalysisData;
using Web.Models.CoreData;
using Web.ViewModel.CoreData;

namespace Web.Service
{
    public  class UserService : BaseService
    {
        
        private UserOp userOp = UserOp.GetInstance();

        private static UserService instance;

        private UserService()
        {

        }

        public static UserService GetInstance()
        {
            if (instance == null)
            {
                instance = new UserService();
            }
            return instance;
        }


        #region User DB Service

        /// <summary>
        /// 获取终端用户信息
        /// </summary>
        /// <returns></returns>
        public UserModel GetUserDetail(String id)
        {
            return new UserModel().ConvertModel(userOp.QueryUserId(id), CompanyOp.GetInstance().QueryAllCompanyList());
        }

        /// <summary>
        /// 获取终端用户信息,用许可号
        /// </summary>
        /// <param name="token">许可号</param>
        /// <returns></returns>
        public User GetUser(String token)
        {
            return userOp.QueryUser(token);
        }

        /// <summary>
        /// 获取所有终端用户
        /// </summary>
        /// <returns></returns>
        public List<UserModel> GetAllUser()
        {
            List<Company> companies = CompanyOp.GetInstance().QueryAllCompanyList();
            return userOp.QueryAllUser().Select(m => new UserModel().ConvertModel(m,companies)).ToList();
        }

       
        /// <summary>
        /// 添加/更新系统用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IServiceResult ModifUser(UserModel model,CompanyModel company)
        {
            if (company==null&&string.IsNullOrEmpty(model.Company))
            {
                return Result(ResultType.ParamIsNull, "请设置公司信息");
            }
            if (string.IsNullOrEmpty(model.Company))
            {
                company = CompanyService.GetInstance().AddCompany(company);
                if(company==null)
                {
                    return Result(ResultType.ParamIsNull, "您填写的公司信息已存在，请勾选并在下拉列表中选择");
                }
                model.Company = company.CompanyId;
            }
            string mmsi = model.MMSI?.Substring(0, model.MMSI.Length - 1);
            IServiceResult result = ModifyShips(mmsi);
            if((ResultType)result.GetCode() != ResultType.Success)
            {
                return result;
            }
            return ModifyUser(model,mmsi);
        }


        /// <summary>
        /// 更新船舶信息
        /// </summary>
        /// <param name="mmsi"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public IServiceResult ModifyShips(String mmsi)
        {
            var result = ShipService.GetInstance().QueryShipXYMMSI(mmsi);
            if (result.status != "0")
            {
                return Result(ResultType.ParamIsError, "请检查输入的MMSI的准确性");
            }
            if (result.data.Count != mmsi.Split(',').Length)
            {
                return Result(ResultType.ParamIsError, "请检查配置的船舶信息是否全部正确");
            }
            List<ShipInfo> list = new List<ShipInfo>();
            foreach (var aisInfo in result.data)
            {
                list.Add(new ShipInfo()
                {
                    Key = generate(aisInfo.mmsi, JsonHelper.SerializeObject(aisInfo)),
                    MMSI = aisInfo.mmsi,
                    Name = aisInfo.name,
                    Value = JsonHelper.SerializeObject(aisInfo.getShipInfoDetail()),
                    Source= 1
                });
            }
            if (!ShipOp.GetInstance().ModifShips(list))
            {
                return Result(ResultType.ParamIsError, "更新船舶信息有误，请重新提交");
            }
            return Result(ResultType.Success);
        }

 

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="mmsi"></param>
        /// <returns></returns>
        public IServiceResult ModifyUser(UserModel model, String mmsi)
        {
            User user = userOp.QueryUserId(model.Id);
            String oldMMSI = user?.MMSI;
            if (user == null)
            {
                if (!String.IsNullOrEmpty(model.Account))
                {
                    if (userOp.QueryUser(model.Account) != null)
                    {
                        return Result(ResultType.ParamIsError, "您配置的许可号已存在");
                    }
                }
                user = new User()
                {
                    Id = model.Id,
                    MMSI = mmsi,
                    Company = model.Company.ToString(),
                    Password = model.Password,
                    Account = model.Account,
                    Register = model.Register,
                    UserName = model.UserName,
                    Configs=model.Configs
                };
                userOp.CreateUser(user);
            }
            else
            {
                user.MMSI = mmsi;
                user.Company = model.Company.ToString();
                user.Password = model.Password;
                user.Account = model.Account;
                user.Register = model.Register;
                user.UserName = model.UserName;
                user.Configs = model.Configs;
                userOp.ModifUser(user);
            }
            
            if (!string.IsNullOrEmpty(mmsi) &&  !oldMMSI.Equals(mmsi))
            {
                UserVesselService.GetInstance().ModifyUserVessel(user);
            }
            return Result(ResultType.Success, "操作成功");
        }
        #endregion





        /// <summary>
        /// 转换
        /// </summary>
        /// <param name="mmsi"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private String generate(string mmsi,string value)
        {
            return JsonHelper.SerializeObject(new ShipKeyModel()
            {
                createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                customKey = mmsi,
                uuid = Guid.NewGuid().ToString(),
                valueHash = Character.MD5.Encrypt(value,"", Encoding.UTF8)
            });
        }

       
    }
}